﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using Rizmar.RizmarDataSetTableAdapters;

namespace Rizmar
{
    public partial class LoginForm : Form
    {
        MainForm referrer;

        public LoginForm()
        {
            InitializeComponent();
        }

        public LoginForm(MainForm refer)
        {
            referrer = refer;
            InitializeComponent();
        }

        private void LoginButton_Click(object sender, EventArgs e)
        {
            RizmarDataSet.UsuarioDataTable udt = new RizmarDataSet.UsuarioDataTable();
            UsuarioTableAdapter uta = new UsuarioTableAdapter();
            udt = uta.Pesquisa(UsernameTextBox.Text, geramd5(PasswordTextBox.Text));
            
            if (udt.Rows.Count > 0)
            {
                this.DialogResult = DialogResult.OK;
                Usuario user = new Usuario(UsernameTextBox.Text,Convert.ToBoolean(udt.Rows[0]["admin"]));
                referrer.setUser(user);
                this.DialogResult = DialogResult.OK;
            }
            else
                MessageBox.Show("Login ou senha errados.");        
        }

        private void ExitButton_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        public string geramd5(string input)
        {
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hash = md5.ComputeHash(inputBytes);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
                sb.Append(hash[i].ToString("x2"));
            return sb.ToString();
        }
    }
}
